<template>
  <div>
    <h1>添加账号</h1>
    <div class="form">
      <el-form :model="formData" :rules="rules" ref="formRef">

        <el-form-item label="账号" prop="account">
          <el-input v-model="formData.account"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="formData.password"></el-input>
        </el-form-item>
        <el-form-item label="用户组" prop="userGroup">
          <el-select v-model="formData.userGroup">
            <el-option value="超级管理员">超级管理员</el-option>
            <el-option value="普通管理员">普通管理员</el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addBtn">添加</el-button>
          <el-button  @click="resetBtn">重置</el-button>
        </el-form-item>

      </el-form>
    </div>



  </div>
</template>

<script setup>

import { reactive,ref } from 'vue';
import { accountAdd } from '@/api/account';
import { ElMessage } from 'element-plus'
const formRef = ref(null)
const formData = reactive({
  account: '',
  password: '',
  userGroup: ''
})


//触发的校验事件函数
const validateAccount = (rule, value, callback) => {
  //rule :整个input的所有的规则  
  //value:当前input的值
  //callback:回调函数，如果校验通过，callback() ，  必须只要写一次验证通过
  //        校验不通过，callback(new Error('错误信息'))
  let reg = /^([a-z]|[0-9]){4,11}$/
  if (reg.test(value)) {
    callback()
  } else {
    callback(new Error('请输入正确的账号'))
  }

}
const validatePassword = (rule, value, callback) => {
  let reg = /^([a-z]|[0-9]){4,11}$/
  if (reg.test(value)) {
    callback()
  } else {
    callback(new Error('请输入正确的密码'))
  }
}

const rules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { validator: validateAccount, trigger: 'blur' }
  ],
  password: [
  {required:true,message:'请输入密码',trigger:'blur'},
  { validator: validatePassword, trigger: 'blur' }

  ],
  userGroup:[
    {required:true,message:'请选择用户组',trigger:'blur'}
  ]
}


const addBtn = () => {
  formRef.value.validate( async (res)=>{
      if(res){
          let {code,msg} = await accountAdd(formData)
          if(code ==0){
            ElMessage.success(msg)
            formRef.value.resetFields()
          }else{
            ElMessage.error(msg)
          }
      }
  })
}

const resetBtn = () => {
  formRef.value.resetFields()
}



</script>

<style scoped lang="scss">
.form {
  width: 500px;
  margin-top: 20px;
}
</style>